﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace JQueryControlToolkit
{
    public interface JSObject
    {
        string ToScript();

        void ToScript(TextWriter toScript);
    }

    public class JSDictionaryObject : JSObject, IEnumerable<KeyValuePair<string,JSObject>>
    {
        private IDictionary<string, JSObject> dictionary = new Dictionary<string, JSObject>();
        public string ToScript()
        {
            StringBuilder sb = new StringBuilder();
            ToScript(new StringWriter(sb));
            return sb.ToString();
        }

        public void ToScript(TextWriter toScript)
        {
            DomOperation.ToScript(toScript, dictionary);
        }

        public void Add(string key, JSObject value)
        {
            dictionary.Add(key, value);
        }

        public void Add(string key, string value)
        {
            dictionary.Add(key, (JSString)value);
        }

        public void Add(string key, int value)
        {
            dictionary.Add(key, new JSString(value.ToString()));
        }

        public IEnumerator<KeyValuePair<string, JSObject>> GetEnumerator()
        {
            return dictionary.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class JSUndefined : JSObject
    {
        public override string ToString()
        {
            return "undefined";
        }

        #region JSObject Members

        public string ToScript()
        {
            return ToString();
        }

        public void ToScript(TextWriter toScript)
        {
            toScript.Write(ToScript());
        }

        #endregion
    }

    public class JSString : JSObject
    {
        string innerValue;

        public JSString(string innerValue)
        {
            this.innerValue = innerValue;
        }

        #region JSObject Members

        public string ToScript()
        {
            return Extensions.ToScript(this);
        }

        public void ToScript(TextWriter toScript)
        {
            toScript.Write(DomResult.Escape(innerValue));
        }

        #endregion

        public static implicit operator JSString(string s)
        {
            return new JSString(s);
        }

        public override string ToString()
        {
            return innerValue;
        }
    }
}
